<?php

Raise::load('core.RaiseStaticClass');
Raise::load('core.reflection.RaiseVariable');
Raise::load('core.helper.config.RaiseSettings');

/**
 * RaiseDbAdapterFactory class
 * Helps to fetch the appropriate DataAccessAdapter based on the settings
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.db.core
 * @since 1.2
 */
class RaiseDbAdapterFactory extends RaiseStaticClass {

    /**
     * Get the right RaiseDbAdapter based on the server type.
     * @param RaiseSettings The settings that this connection is using
     * @param string $type The type of DataAccessAdapter to use. Note that the type here has to be registered in the adapterMap value in the configuration file
     * @return RaiseDbAdapter
     */
    public static function adapter($settings, $type){
        static $map;
        if(!$map){
            if(!($settings instanceof RaiseSettings)){
            throw new RaiseInvalidArgumentException('RaiseDbAdapterFactory::adapter() expecting $settings to be an instance of RaiseSettings, ' . RaiseVariable::typeInfo($settings) . ' given instead.');
            }
            $adapterMap = $settings->get('Database', 'adapterMap');
            if($adapterMap == null){
                throw new RaiseInvalidConfigurationException('Adapter mapping setting [adapterMap] is not found in the section [Database] in the configuration.');
            }
            parse_str($adapterMap, $map);
            unset($adapterMap);
        }
        if(is_array($map) && array_key_exists($type, $map)){
            $a = $map[$type];
            if(!class_exists($a)){
                Raise::load('db.adapter.'.$a);
            }
            return new $a();
        }
        return null;
    }

}